﻿using System;
using Transformable_Engine_v2.Engine.Animation.Trajectory;
using Transformable_Engine_v2.Engine.Global;
using Transformable_Engine_v2.Engine.Transformable_Math.Geometry;

namespace Transformable_Engine_v2.Engine.Animation.PositionAnimation
{
    public class PositionAnimation : BaseAnimation
    {
        public IPositionAnimatable AffectedObject { private get; set; }
        private readonly ITrajectory _trajectory;

        private TE_Vector2 _beginPosition;
        private TE_Vector2 _currentPosition;
        private TE_Vector2 _endPosition;

        public override void Update(TimeSpan gameTime)
        {
            
        }

        public override void FixedStepUpdate(TimeSpan gameTime)
        {
            if(IsAlive() && IsStarted)
            {
                double percentage = _trajectory.GetPercentageProgression(DurationTimer.PercentageElapsed);
                TE_Vector2 nextPosition = (_endPosition - _beginPosition) * percentage + _beginPosition;

                if(AffectedObject != null)
                    AffectedObject.AddToPosition(nextPosition - _currentPosition);
                _currentPosition = nextPosition;
            }

            base.FixedStepUpdate(gameTime);
        }

        protected override void DelayEnd()
        {
            _beginPosition = AffectedObject.GetPosition();

            _currentPosition = _beginPosition;

            base.DelayEnd();
        }

        public override string ToString()
        {
            return string.Format("Movement from {0} to {1}", _beginPosition, _endPosition);
        }

        protected override void DurationEnd()
        {
            if (!IsLooping)
            {
                AffectedObject.AddToPosition(_endPosition - _currentPosition);
                _currentPosition = _endPosition;
            }
            base.DurationEnd();
        }

        public PositionAnimation(ITrajectory trajectory, TE_Vector2 targetPosition,
                                    double duration, bool isLooping = false, double delay = 0, bool autoStart = true)
            : base(duration, isLooping, delay, autoStart)
        {
            _trajectory = trajectory;

            _endPosition = targetPosition.ToGridbound();
        }

        public override void Die()
        {
            //AffectedObject = null;
            base.Die();
        }

    }
}